<template>
  <!-- 添加 | 修改 | 查看弹窗 -->
  <el-dialog :title="`${drawerProps.title}模板`" v-model="drawerVisible" append-to-body center destroy-on-close draggable
    :close-on-click-modal="false" width="640px">
    <el-form ref="ruleFormRef" :model="drawerProps.rowData" :rules="rules" label-width="auto"
      :disabled="drawerProps.title == '查看'">
      <el-form-item label="员工姓名:" prop="fullName">
        <el-input v-model="drawerProps.rowData.fullName" placeholder="请输入员工姓名" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="接口编号:" prop="code">
        <el-select v-model="drawerProps.rowData.code" clearable placeholder="普通单选" popper-class="select-option" >
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="接口名称:" prop="name">
        <el-select v-model="drawerProps.rowData.name" clearable placeholder="多选高度撑开 鼠标移入查看已选择" multiple collapse-tags
          collapse-tags-tooltip :max-collapse-tags="4">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门:" prop="industryType">
        <el-tree-select v-model="drawerProps.rowData!.industryType" :data="appointDeptList" ref="selectRef"
          :props="{ value: 'id', label: 'label', children: 'children' }" show-checkbox value-key="id"
          popper-class="select-option" placeholder="请选择部门（多级加回显）" :render-after-expand="false" @change="changeTree"
          @visible-change="treeFocus" @blur="treeBlur" filterable >
        </el-tree-select>
      </el-form-item>
      <el-form-item label="base URL:" prop="baseUrl" v-if="drawerProps.rowData.status === 2">
        <el-input v-model="drawerProps.rowData.baseUrl" placeholder="请输入base URL" maxlength="1024"></el-input>
      </el-form-item>
      <el-form-item label="api路径:" prop="apiPath">
        <el-input v-model="drawerProps.rowData.apiPath" placeholder="请输入api路径 (长文本区域) " :rows="5" type="textarea"
          show-word-limit maxlength="2000"></el-input>
      </el-form-item>
      <el-form-item label="地点选择:" prop="lng">
        <el-icon :size="30" color="#FA0202" style="cursor: pointer;" @click="openMap">
          <MapLocation />
        </el-icon>
        <span v-if="drawerProps.rowData.lng">
          <!-- {{ drawerProps.rowData.lng }},{{ drawerProps.rowData.lat}}  -->
          {{ drawerProps.rowData.coordinateAddress }}</span>
      </el-form-item>
      <el-form-item label="是否启用:" prop="status">
        <el-radio-group v-model="drawerProps.rowData.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="2">待启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="图片上传:" prop="imgs">
        <ImageUpload v-model="drawerProps.rowData.imgs" />
      </el-form-item>
      <el-form-item label="文件上传:" prop="files">
        <FileUpload v-model="drawerProps.rowData.files" />
      </el-form-item>
      <el-form-item label="审批风格:" prop="status">
        <el-radio-group v-model="drawerProps.rowData.styleColor">
          <el-radio :label="'#f5f5f5'">简约风</el-radio>
          <el-radio :label="'#e0f7fa'">清新风</el-radio>
          <el-radio :label="'#f9f3e3'">温馨风</el-radio>
        </el-radio-group>
      </el-form-item>
      <span class="form-bold">审批流程</span>
      <el-divider border-style="double" />
      <VerticalProcessBar :steps="steps" :current="currentStep" :styleColor="drawerProps.rowData.styleColor">
      </VerticalProcessBar>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit" class="standard-btn">提 交</el-button>
        <el-button @click="drawerVisible = false" class="simple-btn">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <MyMap @getLolaAddress="getLolaAddress" ref="mapRef"></MyMap>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, toRefs, nextTick } from "vue";
import { ElMessage, FormInstance } from "element-plus";
const proxy = getCurrentInstance()?.proxy;
const { sys_user_sex } = toRefs<any>(proxy?.useDict("sys_user_sex"));

//父组件传递参数类型
interface DiolgProps {
  title: string;
  isView: boolean;
  rowData: any;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  [proName: string]: any;
}
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const selectRef = ref(null);
const mapRef = ref(null);
const drawerVisible = ref(false);
const drawerProps = ref<DiolgProps>({
  isView: false,
  title: "",
  rowData: {},
});
const appointDeptList = ref([
  {
    id: 1,
    label: "公司1",
    parentId: 0,
    children: [
      {
        id: 4,
        label: "生产部",
        parentId: 1,
        children: [
          {
            id: 10,
            label: "生产部1",
            parentId: 4,
          },
          {
            id: 11,
            label: "生产部2",
            parentId: 4,
          },
          {
            id: 12,
            label: "生产部3",
            parentId: 4,
          },
        ]
      },
      {
        id: 5,
        label: "销售部",
        parentId: 1,
      }
    ]
  },
  {
    id: 2,
    label: "公司2",
    parentId: 0,
    children: [
      {
        id: 6,
        label: "生产部",
        parentId: 2,
      },
      {
        id: 7,
        label: "销售部",
        parentId: 2,
      }
    ]
  },
  {
    id: 3,
    label: "公司3",
    parentId: 0,
    children: [
      {
        id: 8,
        label: "生产部",
        parentId: 3,
      },
      {
        id: 9,
        label: "销售部",
        parentId: 3,
      }
    ]
  }
]);
const options = [
  {
    value: 'Option1',
    label: 'Option1',
  },
  {
    value: 'Option2',
    label: 'Option2',
  },
  {
    value: 'Option3',
    label: 'Option3',
  },
  {
    value: 'Option4',
    label: 'Option4',
  },
  {
    value: 'Option5',
    label: 'Option5',
  },
  {
    value: 'Option6',
    label: 'Option6',
  },
  {
    value: 'Option7',
    label: 'Option7',
  },
  {
    value: 'Option8',
    label: 'Option8',
  },
]
const steps = [
  {
    label: 'Step 1',
    description: '舟行数日，到得武穴，已是湖北境内。这晚到了福池口，舟子泊了船，准拟过夜，俞莲舟忽听得岸上马嘶声响，向舱外一张，只见两骑马刚好掉转马头，向镇上驰去。',
    name: '明扬',
    status: 'success',
    position: "广知技术部组员",
    time: '2024-07-24 15:27',
    stepAction: "（发起申请）",
    statusName: "已同意",
    statusColor: "#16D700"
  },
  {
    label: 'Step 2',
    description: '舟行数日，到得武穴，已是湖北境内。这晚到了福池口，舟子泊了船，准拟过夜，俞莲舟忽听得岸上马嘶声响，向舱外一张，只见两骑马刚好掉转马头，向镇上驰去。',
    name: '悟空',
    status: 'waring',
    position: "广知技术部主管",
    time: '2024-07-24 15:27',
    stepAction: "（待主管审批）",
    statusName: "已拒绝",
    statusColor: "#EF2222"
  },
  {
    label: 'Step 3',
    description: '舟行数日，到得武穴，已是湖北境内。这晚到了福池口，舟子泊了船，准拟过夜，俞莲舟忽听得岸上马嘶声响，向舱外一张，只见两骑马刚好掉转马头，向镇上驰去。',
    name: 'admin',
    status: 'pending',
    position: "广知技术部主管",
    time: '2024-07-24 15:27',
    stepAction: "（待部门经理审批）",
    statusName: "待审批",
    statusColor: "#999999"
  },
  {
    label: 'Step 4',
    description: '舟行数日，到得武穴，已是湖北境内。这晚到了福池口，舟子泊了船，准拟过夜，俞莲舟忽听得岸上马嘶声响，向舱外一张，只见两骑马刚好掉转马头，向镇上驰去。',
    name: '俞棋辉',
    status: 'pending',
    position: "甬想主管",
    time: '2024-07-24 15:27',
    stepAction: "（待总经理审批）",
    statusName: "待审批",
    statusColor: "#999999"
  },
  {
    label: 'Step 5',
    description: '舟行数日，到得武穴，已是湖北境内。这晚到了福池口，舟子泊了船，准拟过夜，俞莲舟忽听得岸上马嘶声响，向舱外一张，只见两骑马刚好掉转马头，向镇上驰去。',
    name: '刘飞',
    status: 'pending',
    position: "广知主管",
    time: '2024-07-24 15:27',
    stepAction: "（待总经理审批）",
    statusName: "待审批",
    statusColor: "#999999"
  },
]
const currentStep = 1;
// 递归函数，找到所有父级节点并拼接它们的名称
function getParentNames(nodeId) {
  let currentNode = findNodeById(appointDeptList.value, nodeId);
  let parentNames = [];

  while (currentNode) {
    parentNames.unshift(currentNode.label);
    if (currentNode.parentId) {
      currentNode = findNodeById(appointDeptList.value, currentNode.parentId);
    } else {
      currentNode = null;
    }
  }

  return parentNames.join(' - ');
}

function findNodeById(nodes, nodeId) {
  for (let node of nodes) {
    if (node.id === nodeId) {
      return node;
    }
    if (node.children) {
      let foundNode = findNodeById(node.children, nodeId);
      if (foundNode) {
        return foundNode;
      }
    }
  }
  // return null;
}
const treeObj = ref({
  id: "",
  name: ""
})
const changeTree = (v: string | number) => {
  //树形选择回显 这边需要递归
  let name = getParentNames(drawerProps.value.rowData.industryType);
  treeObj.value.id = drawerProps.value.rowData.industryType;
  treeObj.value.name = name;
  nextTick(() => {
    selectRef.value.blur();
    drawerProps.value.rowData.industryType = name;
  })
}
const treeFocus = (visible: boolean) => {
  console.log("visible", visible)
  if (visible) {
    drawerProps.value.rowData.industryType = treeObj.value.id;
  } else {
    drawerProps.value.rowData.industryType = treeObj.value.name;
  }
}
const treeBlur = () => {
  console.log("失去焦点", 1)
  if (drawerProps.value.rowData.industryType) {
    drawerProps.value.rowData.industryType = treeObj.value.name;
  }
}
const getLolaAddress = (location: any) => {
  drawerProps.value.rowData.lng = location.lng;
  drawerProps.value.rowData.lat = location.lat;
  drawerProps.value.rowData.coordinateAddress = location.address;
  // map.value = !map.value;
  console.log("location", location)
}
const openMap = () => {
  mapRef.value.open(drawerProps.value.rowData.coordinateAddress, drawerProps.value.rowData.lng, drawerProps.value.rowData.lat)
}
// 接收父组件传过来的参数
const acceptParams = (params: DiolgProps) => {
  drawerProps.value = params;
  drawerProps.value.rowData.styleColor = '#f5f5f5'
  drawerProps.value.rowData.name = [];
  drawerVisible.value = true;
};

const handleSubmit = () => {
  ruleFormRef.value!.validate(async (valid) => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(drawerProps.value.rowData);
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

const rules = reactive({
  userId: [{ required: true, message: "user表主键不能为空", trigger: "blur" }],
  nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  delFlag: [{ required: true, message: "删除标志不能为空", trigger: "blur" }],
  fullName: [{ required: true, message: "用户姓名不能为空", trigger: "blur" }],
  code: [{ required: true, message: "接口编号不能为空", trigger: "blur" }]
});

defineExpose({
  acceptParams,
});
</script>
